package com.RWM.activities;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONObject;

import com.RWM.helpers.JSONParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Shows create new account screen
 */
public class RegisterActivity extends Activity implements OnClickListener {
  
	int found;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set View to register.xml
        setContentView(R.layout.register);
        
        TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
        Button registerButton = (Button) findViewById(R.id.btn_register_accept);
        
        loginScreen.setOnClickListener(this);
        registerButton.setOnClickListener(this);
    }
	
    public void onClick(View v) {

    	switch(v.getId()){

    	case R.id.link_to_login:
    		// Switching to Login Screen/closing register screen
    		finish();
    		break;

    	case R.id.btn_register_accept: /** AlerDialog when click on Exit */
    		EditText firstname = (EditText) findViewById(R.id.reg_firstname);
    		EditText lastname = (EditText) findViewById(R.id.reg_lastname);
    		EditText uname = (EditText) findViewById(R.id.reg_username);
    		EditText email = (EditText) findViewById(R.id.reg_email);
    		EditText password = (EditText) findViewById(R.id.reg_password);
		  
    		//Ensure all fields have been filled out
    		if(uname.getText().toString().compareTo("")==0 || email.getText().toString().compareTo("")==0 || password.getText().toString().compareTo("")==0
    		   || firstname.getText().toString().compareTo("")==0 || lastname.getText().toString().compareTo("")==0) {
    			Toast.makeText(RegisterActivity.this, "Please fill out all information",
					Toast.LENGTH_LONG).show();
    		}
	      
    		else {
			  
    			//Error checking for duplicate users?
    			/*
					if(usernamefound==1){
    					Toast.makeText(RegisterActivity.this, "Username already exists!",
								Toast.LENGTH_LONG).show();
    				}*/
        		
        		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);  
    			
    			// Adding parameters to send to the HTTP server for login.
        		nameValuePairs.add(new BasicNameValuePair("username", uname.getText().toString()));
    			nameValuePairs.add(new BasicNameValuePair("pw", password.getText().toString()));
    			nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
        		nameValuePairs.add(new BasicNameValuePair("firstname", firstname.getText().toString()));
    			nameValuePairs.add(new BasicNameValuePair("lastname", lastname.getText().toString()));

    			//add user to database
    			String response=createUser(nameValuePairs);
    			
    			if(response.compareTo("{\"rowsAffected\":1}")==0) {
    			Toast.makeText(RegisterActivity.this, "Account has been created",
    					Toast.LENGTH_LONG).show();
    			}
    			else{
    				Toast.makeText(RegisterActivity.this, "Account creation failed",
        					Toast.LENGTH_LONG).show();
    			}
    			
    			finish();

    		}
		  
    		break;
		
    	}    
    }

    public String createUser(List<NameValuePair> nameValuePairs){

    	String url = "http://m.cip.gatech.edu/developer/imf/api/RWMSERVER/user";
    	String serverResponsePhrase;
    	int serverStatusCode=-1;
    	String bytesSent="null";
    	HttpPost httppost = new HttpPost(url);
    	DefaultHttpClient httpclient = new DefaultHttpClient();

    	// Send POST message  with given parameters to the HTTP server.
    	try {                    
    		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

    		HttpResponse response = httpclient.execute(httppost);

    		InputStream is = response.getEntity().getContent();
    		BufferedInputStream bis = new BufferedInputStream(is);
    		ByteArrayBuffer baf = new ByteArrayBuffer(20);

    		int current = 0;  
    		while((current = bis.read()) != -1) {  
    			baf.append((byte)current);  
    		}  

    		bytesSent = new String(baf.toByteArray());

    		// Response from the server          
    		serverResponsePhrase = response.getStatusLine().getReasonPhrase();
    		serverStatusCode = response.getStatusLine().getStatusCode();

    		//Log.v("test", serverResponsePhrase);
    		//Log.v("test", String.valueOf(serverStatusCode));
    		//Log.v("test", String.valueOf(bytesSent));
    		return bytesSent;

    	}
    	catch (Exception e) {
    		Log.e("test", "An error occured while trying to create a user");			
    	}
    	return bytesSent;
    }
    
} 